package com.webank.wedatasphere.qualitis.controller.thymeleaf;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.webank.wedatasphere.qualitis.project.dao.repository.ProjectApprovedRepository;
import com.webank.wedatasphere.qualitis.project.dao.repository.ProjectMuLuRepository;
import com.webank.wedatasphere.qualitis.project.dao.repository.ProjectRepository;
import com.webank.wedatasphere.qualitis.project.entity.Project;
import com.webank.wedatasphere.qualitis.project.entity.ProjectApproved;
import com.webank.wedatasphere.qualitis.project.entity.ProjectMuLu;
import com.webank.wedatasphere.qualitis.response.Grid;
import com.webank.wedatasphere.qualitis.response.Resp;
import com.webank.wedatasphere.qualitis.util.CommUtils;
import com.webank.wedatasphere.qualitis.util.LocalTimeUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/approved")
public class ApprovedController {

    @Autowired
    private ProjectApprovedRepository projectApprovedRepository;


    @Autowired
    private ProjectRepository projectRepository;

    @Autowired
    private ProjectMuLuRepository projectMuLuRepository;

    /**
     * 审批台账
     *
     * @return
     */
    @RequestMapping(value = {"/list"}, method = RequestMethod.GET)
    public ModelAndView list() {
        return new ModelAndView("layui-admin/approved/list");
    }


    /**
     * 审批台账
     *
     * @return
     */
    @RequestMapping(value = {"/detail"}, method = RequestMethod.GET)
    public ModelAndView detail() {
        return new ModelAndView("layui-admin/approved/detail");
    }


    /**
     * 标准编辑修改--发布
     *
     * @param projectList
     * @return
     */
    @RequestMapping(value = {"/modifyStatus"}, method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    @Transactional
    public Resp<?> modifyStatus(HttpServletRequest request, @RequestBody List<Project> projectList) {
        String operation = request.getParameter("operation");
        String thatMsg = request.getParameter("thatMsg");
        try {
            for (Project project : projectList) {
                switch (operation) {
                    case "adopt":
                        project.setFbzt("已发布");
                        projectApproved(project, "审批通过", "admin",thatMsg);
                        break;
                    case "reject":
                        project.setFbzt("已驳回");
                        projectApproved(project, "审批驳回", "admin",thatMsg);
                        break;
                }
                projectRepository.updateStatusFBSuccess(project.getId(), project.getFbzt(), LocalTimeUtils.getCurrentTime());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("审批修改状态失败" + e.getMessage());
        }
        return Resp.Ok();
    }

    private void projectApproved(Project project, String status, String userName, String thatMsg) {
        // 进入审批流
        List<ProjectApproved> byApprovedBiaoZunId = projectApprovedRepository.findByApprovedBiaoZunId(project.getId());
        Long approvedVersion = 1L;
        if (CollectionUtils.isNotEmpty(byApprovedBiaoZunId)) {
            // 获取审批流中最新的一条
            ProjectApproved projectApproved = byApprovedBiaoZunId.stream().min((o1, o2) -> o2.getApprovedVersion().compareTo(o1.getApprovedVersion())).get();
            approvedVersion = projectApproved.getApprovedVersion() + 1;

        }
        ProjectApproved projectApproved = new ProjectApproved();
        projectApproved.setApprovedMsg(thatMsg);
        projectApproved.setApprovedBiaoZunId(project.getId());
        projectApproved.setApprovedTime(LocalTimeUtils.getCurrentTime());
        projectApproved.setApprovedOperation(status);
        projectApproved.setApprovedUser(userName);
        projectApproved.setApprovedVersion(approvedVersion);
        projectApprovedRepository.save(projectApproved);
    }

    /**
     * EasyUI分页
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/datagrid"}, method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public Grid<?> datagrid(HttpServletRequest request) {
        Sort sort = new Sort(Sort.Direction.DESC, "modifyTime");
        //  分页查询
        String page = request.getParameter("page");
        String limit = request.getParameter("rows");
        // 获取条件过滤器
        JSONObject changeBuilder = CommUtils.getJsonObject(request);
        // 组装SQl条件过滤法器
        ExampleMatcher matcher = CommUtils.getSqlWhere(request);
        // 序列化对象
        Project itemQueryWhere = changeBuilder.toJavaObject(Project.class);
        String thatFbzt = request.getParameter("thatFbzt");
        // 只能审批发布中的数据
        itemQueryWhere.setFbzt(thatFbzt);
        // 分页插件
        Pageable pageable = PageRequest.of(Integer.parseInt(page) - 1, Integer.parseInt(limit), sort);
        // 条件过滤器插件
        Example<Project> example = Example.of(itemQueryWhere, matcher);
        // 条件过滤+分页
        Page<Project> all = projectRepository.findAll(example, pageable);
        // 获取目录翻译所属目录
        List<ProjectMuLu> muLuRepositoryAll = projectMuLuRepository.findAll();
        for (Project project : all) {
            for (ProjectMuLu projectMuLu : muLuRepositoryAll) {
                if (StringUtils.isNotBlank(project.getSjzlbzml()) && project.getSjzlbzml().equals(projectMuLu.getId().toString())) {
                    project.setSjzlbzml(projectMuLu.getTitle());
                }
            }
        }
        List<Project> content = all.getContent();
        long totalElements = all.getTotalElements();
        return Grid.OkPage(CollectionUtils.isEmpty(content)?new ArrayList<>():content, totalElements);
    }

}